﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using FarPoint.Win.Spread;
using FarPoint.Win.Spread.CellType;
using Spread.Common.DataStore;
using Spread.Common.DataStore.DataSourceEntities;
using Spread.Common.DataStore.Models;

namespace GrapeCity.StudentCalendar
{
    public partial class StudentCalendarControl : Spread.Common.Features.Sample.BaseSampleControl
    {
        #region Fields
        private DateTimeFormatInfo _dateTimeFormatInfo;
        private StudentCalendarDataSource _dataSource;
        private List<ScheduleEntry> _schedule;
        private List<Assignment> _assignments;
        #endregion

        #region ctor
        public StudentCalendarControl()
        {
            InitializeComponent();

            _dateTimeFormatInfo = new DateTimeFormatInfo();
            _dataSource = new DataService().StudentCalendarDataSource;
            _schedule = _dataSource.GetSchedule();
            _assignments = _dataSource.GetAssignments(DateTime.Now.Year);

            Load += Form1_Load;
            fpSpread.Change += FpSpread_Change;
        }
        #endregion

        #region Event handlers
        private void FpSpread_Change(object sender, ChangeEventArgs e)
        {
            SheetView sheet = fpSpread.Sheets[e.View.ActiveSheetIndex];
            if (sheet.SheetName == "January" && e.Row == 1 && e.Column == 13)
            {
                bool isYearValid = false;
                int year = -1;
                isYearValid = int.TryParse(sheet.Cells[e.Row, e.Column].Text, out year);

                DateTime date = DateTime.MinValue;
                isYearValid = DateTime.TryParse($"1/1/{year}", out date);

                // Clear Assignment and Weekly Schedule
                _assignments = _dataSource.GetAssignments(year);
                for (int month = 1; month <= 12; ++month)
                {
                    if (isYearValid)
                    {
                        _assignments = _dataSource.GetAssignments(year);
                        AddAssignmentsToSheet(month);
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            fpSpread.SuspendLayout();
            fpSpread.OpenExcel(@"Template\StudentCalendar.xlsx");
            fpSpread.TabStripInsertTab = false;

            for (int i = 0; i < fpSpread.Sheets.Count; ++i)
            {
                SetSheetProperties(fpSpread.Sheets[i]);
                AddCalendarToSheet(i + 1);
                AddAssignmentsToSheet(i + 1);
            }

            fpSpread.ResumeLayout(true);
        }
        #endregion

        #region Private methods
        private void SetSheetProperties(SheetView sheet)
        {
            sheet.ColumnHeader.Visible = false;
            sheet.RowHeader.Visible = false;
            sheet.HorizontalGridLine = new GridLine(GridLineType.None);
            sheet.VerticalGridLine = new GridLine(GridLineType.None);
        }

        private void AddCalendarToSheet(int month)
        {
            if (month < 1 || month > 12)
                throw new ArgumentException("month must be between 1 and 12");
            string monthName = _dateTimeFormatInfo.MonthNames[month - 1];
            SheetView sheet = fpSpread.Sheets.Find(monthName);
            if (sheet == null)
                throw new Exception($"Could not find sheet for the month of {monthName}");

            DateTimeCellType dateCell = new DateTimeCellType();
            dateCell.DateTimeFormat = DateTimeFormat.UserDefined;
            dateCell.UserDefinedFormat = "d";

            int year = DateTime.Now.Year;
            if (month == 1)
            {
                sheet.Cells[1, 13].Value = year;
                sheet.Cells[1, 13].Locked = false;
            }
            sheet.Cells[1, 1].Value = month;
            sheet.Cells[6, 1].Value = _dateTimeFormatInfo.AbbreviatedMonthNames[month - 1];

            int baseRow = 3, baseCol = 2, offset = 1;
            for (int r = 0; r < 6; ++r)
            {
                for (int c = 0; c < 7; ++c)
                {
                    sheet.Cells[baseRow + r, baseCol + c].Formula = $"DATE(CALENDARYEAR, {month}, 1) - " +
                        $"WEEKDAY(DATE(CALENDARYEAR, {month}, 1)) + {offset++}";
                    sheet.Cells[baseRow + r, baseCol + c].CellType = dateCell;
                }
            }

            AddWeeklySchedule(sheet);
        }

        private void AddAssignmentsToSheet(int month)
        {
            if (month < 1 || month > 12)
                throw new ArgumentException("month must be between 1 and 12");
            string monthName = _dateTimeFormatInfo.MonthNames[month - 1];
            SheetView sheet = fpSpread.Sheets.Find(monthName);
            if (sheet == null)
                throw new Exception($"Could not find sheet for the month of {monthName}");

            sheet.Cells[3, 11, 31, 12].ResetValue();
            sheet.ClearRange(3, 11, 29, 2, true);
            List<Assignment> currentMonthAssignments = _assignments.Where(asgnmt => asgnmt.Date.Month == month).
                ToList();

            int baseRow = 3, col = 11;
            DayOfWeek dayOfWeek = DayOfWeek.Monday;
            while (dayOfWeek != DayOfWeek.Saturday)
            {
                List<Assignment> assignments = currentMonthAssignments.Where(asgnmt => asgnmt.Date.DayOfWeek == dayOfWeek).
                    ToList();
                for (int i = 0; i < Math.Min(assignments.Count, 5); ++i)
                {
                    sheet.Cells[baseRow + i, col].Value = assignments[i].Date.Day;
                    sheet.Cells[baseRow + i, col + 1].Value = assignments[i].Description;
                }
                dayOfWeek = (DayOfWeek)((int)dayOfWeek + 1);
                baseRow += 6;
            }
        }

        private void AddWeeklySchedule(SheetView sheet)
        {
            int row = 13, col = 1;
            for (int i = 0; i < _schedule.Count; ++i)
            {
                sheet.Cells[row + (i / 5) * 2, col].Value = $"{_schedule[i].Hour:00}:00";
                sheet.Cells[row + (i / 5) * 2 + 1, col].Value = _schedule[i].Subject;

                col += (i % 5 == 0) ? 1 : 2;
                if ((i + 1) % 5 == 0)
                    col = 1;
            }
        }
        #endregion
    }
}


//
//StudentCalendarControl.Designer.cs
//


namespace GrapeCity.StudentCalendar
{
    partial class StudentCalendarControl
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.fpSpread = new FarPoint.Win.Spread.FpSpread(FarPoint.Win.Spread.LegacyBehaviors.None);
            this.fpSpread_Sheet1 = new FarPoint.Win.Spread.SheetView();
            this.pnlMain.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread_Sheet1)).BeginInit();
            this.SuspendLayout();
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.fpSpread);
            // 
            // fpSpread
            // 
            this.fpSpread.AccessibleDescription = "";
            this.fpSpread.Dock = System.Windows.Forms.DockStyle.Fill;
            this.fpSpread.Location = new System.Drawing.Point(0, 0);
            this.fpSpread.Name = "fpSpread";
            this.fpSpread.Sheets.AddRange(new FarPoint.Win.Spread.SheetView[] {
            this.fpSpread_Sheet1});
            this.fpSpread.Size = new System.Drawing.Size(477, 487);
            this.fpSpread.TabIndex = 0;
            // 
            // fpSpread_Sheet1
            // 
            this.fpSpread_Sheet1.Reset();
            this.fpSpread_Sheet1.SheetName = "Sheet1";
            // Formulas and custom names must be loaded with R1C1 reference style
            this.fpSpread_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;
            this.fpSpread_Sheet1.ColumnFooter.DefaultStyle.BackColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.ColumnFooter.DefaultStyle.ForeColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.ColumnFooterSheetCornerStyle.BackColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.ColumnFooterSheetCornerStyle.ForeColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.ColumnHeader.DefaultStyle.BackColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.ColumnHeader.DefaultStyle.ForeColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.RowHeader.DefaultStyle.BackColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.RowHeader.DefaultStyle.ForeColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.SheetCornerStyle.BackColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.SheetCornerStyle.ForeColor = System.Drawing.Color.Empty;
            this.fpSpread_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1;
            // 
            // StudentCalendarControl
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "StudentCalendarControl";
            this.pnlMain.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread_Sheet1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private FarPoint.Win.Spread.FpSpread fpSpread;
        private FarPoint.Win.Spread.SheetView fpSpread_Sheet1;
    }
}
